<?php


namespace app\pipeline\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\pipeline\model\Business as BusinessModel;
use app\company\model\Company as CompanyModel;
use app\pipeline\model\Equipment as EquipmentModel;
use app\pipeline\model\Pipe as PipeModel;
use app\pipeline\model\Checklog as ChecklogModel;
use app\user\model\User;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;

class Business extends Admin
{
    //业务列表
    public function index(){
        $map=$this->getMap();
        if($this->user_auth['role']!==1&&$this->user_auth['company_id']!==0){
            $map[]=['company_id','=',$this->user_auth['company_id']];
        }
        $data_list = BusinessModel::where($map)->order('id','desc')->paginate()->each(function($value){
            $value['company_id']=CompanyModel::where('id',$value['company_id'])->value('name');
            $value['has_checklog']=ChecklogModel::where('business_id',$value['id'])->count(1);
            $value['creater']=User::where('id',$value['creater'])->value('nickname');
            $value['equipment_number']=EquipmentModel::where('id',$value['equipment_number'])->value('number');
            $value['pipeline_number']=PipeModel::whereIn('id',$value['pipeline_number'])->column('number');
            $value['status_cn']=$value['status'] == 0 ? "待执行" : ($value['status'] == 1 ? "进行中" : "已完成");
            if(is_array($value['pipeline_number'])){
                $value['pipeline_number']=implode("<br/>",$value['pipeline_number']);
            }
        });

        return ZBuilder::make('table')
            ->setPageTitle('业务管理') // 页面标题
            ->setTableName('equipment') // 设置表名
            ->setSearch([
                'equipment_number' => '设备编号',
                'pipeline_number'=>'管道编号',
                'title'=>'业务标题',
                'id' => 'ID']
            ) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['title', '业务名称'],
                ['equipment_number','设备编号'],
                ['pipeline_number', '管道编号'],
                ['address', '业务地址'],
                ['creater', '业务添加人'],
                ['status_cn','业务状态'],
                ['create_time', '业务添加时间'],
                ['complete_time', '业务结束时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButtons(
                [
                    'edit'=> ['title'=>'编辑','href' => url('business_save', ['id' => '__id__'])],
                    'delete'=>['title'=>'删除','href'=>url('business_del',['id'=>'__id__'])]
                ]
            )
            ->addRightButton('export',[
                'title'=>'导出WORD',
                'icon' =>'fa fa-fw fa-th',
                'href' =>url('export_word',['id'=>'__id__']),
            ])
            ->addRightButton('view' ,[
            'title' => '查看测点记录',
            'icon'=>'fa fa-fw fa-eye',
            'class'=>'btn btn-xs btn-default',
            'href'=>url('checklog/index',['id'=>'__id__','_pop'=>1])],
            ['area' => ['90%', '100%']]
            )
            ->addRightButton('offtask' ,[
                    'title' => '结束业务',
                    'icon'=>'fa fa-fw fa-stop',
                    'class'=>'btn btn-xs btn-default ajax-get confirm',
                    'href'=>url('offbusiness',['id'=>'__id__']),
                    'data-title' => '确定要结束当前业务？',
                    'data-tips' => '结束了就无法恢复了'
            ])
            ->replaceRightButton(['has_checklog' => ['eq', '0']], '', ['export','view'])
            ->replaceRightButton(['status'=>['neq','0']],'',['delete'])
            ->replaceRightButton(['status'=>['eq','2']],'',['offtask'])
            ->addTopButton('add',['href'=>url('business_save')])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    //业务添加编辑
    public function business_save(){
        if($this->user_auth['company_type']=='third_slave'){
            $this->error('无权添加业务');
            }
        if($this->request->isPost()){
            $data=$this->request->post();
            if(!empty($data['pipeline_company'])){//第三方和管理员添加
                $data['pipeline_company']=implode(',',$data['pipeline_company']);
            }else{//普通有设备用户添加
                $data['pipeline_company']=$this->user_auth['company_id'];
            }

            $where=[];
            $where['title']=$data['title'];
            $where['company_id']=$this->user_auth['company_id'];
            $has_title=BusinessModel::where($where)->value('id');
            if($has_title){
                if(!empty($data['id'])){
                    if($has_title!=$data['id']){
                        $this->error('修改失败,已存相同名称业务');
                    }
                }else{
                    $this->error('添加失败,已存相同名称业务');
                }
            }

            if($this->user_auth['role']!==1&&$this->user_auth['company_id']!==0){
                $data['company_id']=$this->user_auth['company_id'];
            }
            //验证
            $result = $this->validate($data, 'Business');
            if(true !== $result) $this->error($result);
            //超管操作验证
            if($this->user_auth['role']==1&&$this->user_auth['company_id']==0){
                $equipment_name=EquipmentModel::where("company_id",$data['company_id'])
                    ->where('id',$data['equipment_number'])
                    ->value('name');
                if(!$equipment_name){
                    $this->error('设备'.$equipment_name.',不属于当前公司无法添加');
                }
                $company_type=CompanyModel::where('id',$data['company_id'])->value('company_type');
                if($company_type=='third'){//第三方添加时验证
                    $company_ids=CompanyModel::where('b_company',$data['company_id'])->column('id');
                    $pipeline_number=PipeModel::whereIn("company_id",$company_ids)
                        ->whereIn('id',implode(',',$data['pipeline_number']))
                        ->column('id');
                }else{
                    $pipeline_number=PipeModel::where("company_id",$data['company_id'])
                        ->whereIn('id',implode(',',$data['pipeline_number']))
                        ->column('id');
                }

                $diff=array_diff($data['pipeline_number'],$pipeline_number);
                if($diff){
                    $pipe_name=PipeModel::where('number',array_pop($diff))->value('name');
                    $this->error('管道'.$pipe_name.',的操作权限不属于当前公司无法添加');
                }
            }
            $data['pipeline_number']=implode(',',$data['pipeline_number']);
            $data['creater']=$this->user_auth['uid'];
            Db::startTrans();
            try{
                //业务添加时设备使用次数+1
                if(!empty($data['id'])){
                    //编辑
                    $res=BusinessModel::update($data);
                    if(!$res){
                        Db::rollback();
                        $this->error('保存失败');
                    }
                    action_log('business_edit','business',$data['id'],UID,json_encode($data,JSON_UNESCAPED_UNICODE));
                }else{
                    //添加
                    $res=BusinessModel::create($data);
                    $equipment_number=$data['equipment_number'];
                    $equi_res=EquipmentModel::where('id',$equipment_number)->setInc('use_time',1);
                    if(!$res||!$equi_res){
                        Db::rollback();
                        $this->error('保存失败');
                    }
                    action_log('business_add','business',$res['id'],UID,'--业务ID:'.$res['id']);
                }
                Db::commit();
                $this->success('保存成功','index');
            }catch(Exception $e){
                Db::rollback();
                halt($e->getMessage());
                $this->error('保存失败');
            }
        }

        // 显示编辑页面
        $id=$this->request->param('id');
        $info=BusinessModel::get($id);
        $zbuilder = ZBuilder::make('form')
            ->setPageTitle('编辑业务信息')
            ->setPageTips('请谨慎操作', 'warning');

        //管理员添加
        if($this->user_auth['role']==1&&$this->user_auth['company_id']==0){
            $company_list = CompanyModel::where('company_type','neq','third_slave')->column('name','id');
            if(!empty($info)){
                $equipment_list=EquipmentModel::where('company_id',$info['company_id'])->column('name','id');
                $company_type=CompanyModel::where('id',$info['company_id'])->value('company_type');
                if($company_type=='third'){
                    $pipeline_company=CompanyModel::where('b_company',$info['company_id'])->column('name','id');
                    $pipeline_number=PipeModel::whereIn('company_id',array_keys($pipeline_company))->column('name','id');
                }else{
                    $pipeline_company=CompanyModel::where('id',$info['company_id'])->column('name','id');
                    $pipeline_number=PipeModel::whereIn('company_id',$info['company_id'])->column('name','id');
                }
            }
            $zbuilder->addLinkage('company_id', '设备所属公司', '<span class="text-danger">必填</span>', $company_list, $info['company_id'], url('ajax_get_equipment'), 'equipment_number','','company_id')
                     ->addSelect('equipment_number', '选择设备', '<span class="text-danger">必填</span>', !empty($equipment_list)?$equipment_list:'')
                     ->addSelect('pipeline_company','选择管道所属公司','<span class="text-danger">必填</span>',!empty($pipeline_company)?$pipeline_company:'','','multiple')
                     ->addSelect('pipeline_number','选择管道','<span class="text-danger">必填</span>',!empty($pipeline_number)?$pipeline_number:'','','multiple');
            //剩余交互在JS完成
        }else{
            //非管理员添加,第三方和自带设备
            $equipment_list=EquipmentModel::where('company_id',$this->user_auth['company_id'])->column('name','id');
            //第三方检测机构添加业务,管道为第三方的客户公司
            if($this->user_auth['company_type']=='third'){
                $equipment_list=EquipmentModel::where('company_id',$this->user_auth['company_id'])->column('name','id');
                $slave_company=CompanyModel::where('b_company',$this->user_auth['company_id'])->column('name','id');
                $pipeline_list=PipeModel::whereIn('company_id',array_keys($slave_company))->column('name','id');
                $zbuilder->addSelect('equipment_number','选择设备','<span class="text-danger">必填</span>',$equipment_list);
                $zbuilder->addSelect('pipeline_company','管道所属公司','<span class="text-danger">必填</span>',$slave_company,'','multiple');
                if(!empty($info)){
                    $zbuilder->addSelect('pipeline_number','管道','<span class="text-danger">必填</span>',$pipeline_list,'','multiple');
                }
            }else{
                //自带设备
                $zbuilder->addSelect('equipment_number', '选择设备', '请选择设备',$equipment_list);
                $pipeline_list=PipeModel::where('company_id',$this->user_auth['company_id'])->column('name','id');
                $zbuilder->addSelect('pipeline_number', '选择管道', '请选择管道',$pipeline_list,$info['pipeline_number'],'multiple');
            }
        }
        return $zbuilder->addFormItems([
                ['hidden', 'id'],
                ['text', 'title', '业务名称', '<span class="text-danger">必填</span>'],
                ['text', 'description', '业务描述'],
                ['text','address', '业务地址']
            ])
            ->setFormData($info)
            ->js('company_get_pipeline')
            ->fetch();
    }
    //下拉联动获取添加业务时所需设备
    public function ajax_get_equipment(){
        if($this->request->isAjax()){
            $re_data=[];
            $company_id=$this->request->param('company_id');
            $company_info=CompanyModel::where('id',$company_id)->field('b_company,company_type')->find();
            $where=[];
            if($company_info['company_type']=='third_slave'){
                $where['company_id']=$company_info['b_company'];
            }else{
                $where['company_id']=$company_id;
            }
            $equipment_info=EquipmentModel::field('`id` as `key`,`name` as `value`')
                ->where($where)->select();
            $re_data['code'] = 1;
            $re_data['msg'] = '获取设备信息成功';
            $re_data['list']=$equipment_info;
            if(!$equipment_info){
                $re_data['code']=0;
                $re_data['msg']='获取设备信息失败';
            }
            return json($re_data);
        }
        return false;
    }
    //下拉联动获取添加业务时所需管道信息
    public function ajax_get_pipeline(){
        if($this->request->isAjax()){
            $company_ids=$this->request->param('company_id');
            $pipe_list=PipeModel::field('id,name')->whereIn('company_id',$company_ids)->select();
            $data['message']='获取管道信息成功';
            $data['code']=true;
            if(!$pipe_list){
            $data['message']='获取管道信息失败';
            $data['code']=false;
            }
            $data['data']=$pipe_list;
            return json($data);
        }
        return false;

    }
    //根据公司类型返回不同表单选项
    public function ajax_get_pipecompany(){
        $equipment_number=$this->request->param('equipment_number');
        $company_id=EquipmentModel::where('id',$equipment_number)->value('company_id');
        $company_type=CompanyModel::where('id',$company_id)->value('company_type');
        if($company_type=='third'){
            $company_list=CompanyModel::field('id,name')->where('b_company',$company_id)->select();
        }else{
            $company_list=CompanyModel::field('id,name')->where('id',$company_id)->select();
        }
        $data=[];
        $data['message']='获取失败';
        $data['code']=0;
        if($company_list){
            $data['message']='根据设备获取管道信息成功';
            $data['code']=1;
        }
        $data['data']=$company_list;
        return json($data);
    }
    //业务删除
    public function business_del(){
        $id=$this->request->param('id');
        $has_business=BusinessModel::where("id",$id)->find();
        if(!$has_business){
            $this->error('未找到相关业务信息');
        }
        $del_result=BusinessModel::where("id",$id)->delete();
        if(!$del_result){
            $this->error('删除失败');
        }
        action_log('business_del','business',$id,UID,json_encode($has_business,JSON_UNESCAPED_UNICODE));
        $this->success('删除成功');
    }
    //结束业务
    public function offbusiness()
    {
        $business_id = $this->request->param('id');
        $res = BusinessModel::where('id', $business_id)->update(['status' => 2,'complete_time'=>date('Y-m-d H:i:s')]);
        if (!$res) {
            $this->error('结束业务失败,请重试');
        }
        $this->success('结束业务成功');
    }
    //根据word模板导出业务详细信息
    public function export_word(){
        $business_id=$this->request->param('id');
        $row_log=ChecklogModel::field('pipeline_number,business_id')
            ->where('business_id',$business_id)
            ->group('pipeline_number,business_id')
            ->select();
        $business_info=BusinessModel::where("id",$business_id)->find();
        $equipment_info=EquipmentModel::where("number",$business_info['equipment_number'])->find();
        //创建压缩文件
        $zipTool = new \ZipArchive();
        $time = date('ymd', strtotime($business_info['create_time']));
        $zippath=FILE_PATH.'zip/'.$time.'/';
        $zip_name='业务'.$business_id.'检测报告.zip';
        $zip_file=$this->mkfile_dir($zippath,$zip_name);
        if(file_exists($zip_file)) unlink($zip_file);
        $open = $zipTool->open($zip_file, \ZipArchive::CREATE);
        //遍历处理测点信息
        foreach ($row_log as $val){
            $data=[];
            $pipe_info=PipeModel::where('id',$val['pipeline_number'])->find();
            $data['pipeline_name']=$pipe_info['name'];
            $data['pipeline_number']=$pipe_info['number'];
            $data['specifications']=$pipe_info['specifications'];
            $data['material']=$pipe_info['material'];
            $data['surface']=$pipe_info['surface'];
            $data['level']=$pipe_info['level'];
            $where=[];
            $where[]=['pipeline_number','=',$val['pipeline_number']];
            $where[]=['business_id','=',$val['business_id']];
            $data['logs']=ChecklogModel::field('thickness,sort,center,business_id')->where($where)->order('sort','asc')->select()->toArray();
            $point_number=count($data['logs']);
            $thickness=min(array_column($data['logs'],'thickness'));
            //填入DOC模板变量
            $tmp = new TemplateProcessor(UPLOAD_PATH.'business_export_temp.docx');
            $tmp->setValue('pipeline_name',$data['pipeline_name']);//管道名称
            $tmp->setValue('pipeline_number',$data['pipeline_number']);//管道编号
            $tmp->setValue('specifications',$data['specifications']);//规格
            $tmp->setValue('material',$data['material']);//材质
            $tmp->setValue('surface',$data['surface']);//表面状况
            $tmp->setValue('level',$data['level'].'级');//等级
            $tmp->setValue('point_number',$point_number.'个');//测点总数
            $tmp->setValue('min_thickness',$thickness);//最小壁厚
            $tmp->setValue('equipment_type',$equipment_info['type']);//设备型号
            $tmp->setValue('equipment_accuracy',$equipment_info['accuracy']);//设备精度
            $address=$business_info['address'];
            $chunk_data=array_chunk($data['logs'],50);//地图标注只能最多50个
            $map_times=count($chunk_data);
            $tmp->cloneRow('map_url',$map_times);

            foreach($chunk_data as $k=>$row_data){
                $row_center=array_column($row_data,'center');
                $row_sort=array_column($row_data,'sort');
                $short_range=reset($row_sort).'-'.end($row_sort);
                $tmp->setValue('sort_range#'.($k+1),$short_range);
                $map_data=[];
                $map_data['center']=$this->getLngLat($address);
                $map_data['marker_style']='';
                foreach($row_data as $r){
                    $map_data['marker_style'].='s|';
                }
                $map_data['markers']=implode('|',$row_center);
                $map_data['paths']=implode(';',$row_center);
                $map_path=$this->staticimage($map_data,$data['pipeline_number'].($k+1));
                //图片
                $tmp->setImageValue('map_url#'.($k+1),['path'=>$map_path,'width'=>550,'height'=>500]);
            }

            //填充测点
            if(ceil($point_number/4)>1){
                $rows=ceil(count($data['logs'])/4);
                $tmp->cloneRow('index1',$rows);
                $new_array=[];
                for ($i = 0; $i < ceil($point_number); $i++) {
                    $new_array[] = array_slice($data['logs'], $i * 4, 4);
                }
                $new_array=array_filter($new_array);
                foreach ($new_array as $k => $v) {
                    $row=$k+1;
                    for ($i = 0; $i <= 4; $i++) {
                        $index = $i + 1;
                        if (!empty($v[$i])) {
                            $tmp->setValue("index$index#" . $row, $v[$i]['sort']);
                            $tmp->setValue("thickness$index#" . $row, $v[$i]['thickness']);
                        } else {
                            $tmp->setValue("index$index#" . $row, " ");
                            $tmp->setValue("thickness$index#" . $row, "  ");
                        }
                    }
                }
            }else{
                sort($data['logs']);
                for($i=0;$i<=4;$i++){
                    $row=$i+1;
                    if(!empty($data['logs'][$i])){
                        $tmp->setValue('index'.$row,$data['logs'][$i]['sort']);
                        $tmp->setValue('thickness'.$row,$data['logs'][$i]['thickness']);
                    }else{
                        $tmp->setValue('index'.$row," ");
                        $tmp->setValue('thickness'.$row," ");
                    }
                }
            }
            $time = date('ymd', strtotime($business_info['create_time']));
            $path=FILE_PATH.'doc/'.$time.'/';
            $file_name=$val['pipeline_number'] . $time . '检测报告' . ".docx";
            $doc_path=$this->mkfile_dir($path,$file_name);
            $tmp->saveAs($doc_path);
            //写入压缩文件
            if($open) $zipTool->addFile($doc_path,$file_name);

        }
        if($open) $zipTool->close();
        if(!file_exists($zip_file)){
            exit("无法找到文件"); //即使创建，仍有可能失败。。。。
        }
        // $zip_file = iconv("utf-8","gb2312",$zip_file);   //防止有的浏览器下载之后中文乱码
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($zip_file)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($zip_file)); //告诉浏览器，文件大小
        @readfile($zip_file);
        unlink($zip_file);

    }
    /*
     * 根据地址来获取经纬度
     */
    public  function getLngLat($address){
        $data=[
            'address' => $address,
            'output'  => 'json',
            'ak'      => config('keys.baidu_map_ac')
        ];

        // 转换成上面形式
        $url = 'http://api.map.baidu.com/geocoding/v3/'.'?'.http_build_query($data);
        $result = file_get_contents($url);
        if($result){
            $res=json_decode($result,true);
            if($res['status']!==0){
                $this->error('未找到业务`地址中心');
            }
            $location=$res['result']['location'];
            $center=implode(',',$location);
            return $center;
        }else{
            return [];
        }

    }
    /**  http://api.map.baidu.com/staticimage/v2
     *   根据经纬度获取百度静态地图保存到本地
     *   @param $center
     */
    public  function staticimage($map_data,$unicode){
        if(!$map_data){
            return '';
        }
        $data = [
            'ak' => config('keys.baidu_map_ac'),
            'width' => '700',
            'height' => '500',
            'center' => $map_data['center'],
            'markers' => $map_data['markers'],
            'markerStyles'=>$map_data['marker_style'],
            'paths'=>$map_data['paths'],
            'pathStyles'=>'0xff0000,3,1'
        ];

        $url = 'http://api.map.baidu.com/staticimage/v2'.'?'.http_build_query($data);
        $result = file_get_contents($url);
        $time = date('ymd', time());
        $path = $path = UPLOAD_PATH.'images/'.$time.'/';
        if (!is_dir($path)){
            $res = mkdir($path,0777,true);
            if (!$res) {
                return false;
            }
        }
        $new_file = $path.$unicode.".png";
        if (file_put_contents($new_file,$result)){
            return $new_file;
        }else{
            return false;
        }
    }












}